﻿using DevExpress.Web.ASPxUploadControl;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using Utility1;

namespace eDream.admin
{
    public partial class addProduct : System.Web.UI.UserControl
    {
        public string pathUrl = "";
        const string UploadDirectory = "~/Image/product/";
        protected void Page_Load(object sender, EventArgs e)
        {
            pathUrl = WebUtils.pathUrl() + "/Image/product/";
            if (!IsPostBack)
            {
                LoadCBX();
                radChitiet.Language = "vi";
                //CKEditorControl1.config.filebrowserImageBrowseUrl = "/ckfinder/ckfinder.html?type=Images";
                //CKEditorControl1.config.filebrowserImageUploadUrl = "/ckfinder/core/connector/aspx/connector.aspx?command=QuickUpload&type=Images";
                CKFinder.FileBrowser _FileBrowser = new CKFinder.FileBrowser();
                _FileBrowser.BasePath = "/ckfinder/";
                _FileBrowser.SetupCKEditor(radChitiet);
                _FileBrowser.SetupCKEditor(radHinhanh);
                _FileBrowser.SetupCKEditor(radTinhnang);
                _FileBrowser.SetupCKEditor(radVideo);

                Bindata();
            }
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {

        }

        protected void uplImage_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
        {
            e.CallbackData = SavePostedFile(e.UploadedFile, 0, 290);
        }

        string SavePostedFile(UploadedFile uploadedFile, int index, int size)
        {
            if (uploadedFile.FileName == "")
                return string.Empty;

           // Random r = new Random(9999);
           // int n = r.Next(999999);
            string ThumbnailFileName = uploadedFile.FileName;
            string fileName = Path.Combine(MapPath(UploadDirectory), ThumbnailFileName);
            string urpath2 = Path.Combine("/subdomains/tintuc/httpdocs/image/New/");
            lbthongbao.Text = fileName;
            using (Image original = Image.FromStream(uploadedFile.FileContent))
            using (Image thumbnail = PhotoUtils.Inscribe(original, size))
            {
               // PhotoUtils.SaveToJpeg(thumbnail, fileName);
                ImageHandler h = new ImageHandler();
                h.Save(thumbnail, size, size, 90, fileName);
            }
            switch (index)
            {
                case 0:
                    Session["link0"] = ThumbnailFileName;
                    break;
                case 1:
                    Session["link1"] = ThumbnailFileName;
                    break;
                case 2:
                    Session["link2"] = ThumbnailFileName;
                    break;
                case 3:
                    Session["link3"] = ThumbnailFileName;
                    break;
                case 4:
                    Session["link4"] = ThumbnailFileName;
                    break;
                case 5:
                    Session["link5"] = ThumbnailFileName;
                    break;
                case 6: Session["link6"] = ThumbnailFileName;
                    break;
            }
            Session.Timeout = 120;
            return ThumbnailFileName;
        }

        protected void uplImage1_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
        {
            e.CallbackData = SavePostedFile(e.UploadedFile, 1, 320);
        }

        protected void uplImage2_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
        {
            e.CallbackData = SavePostedFile(e.UploadedFile, 2, 320);
        }

        protected void uplImage3_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
        {
            e.CallbackData = SavePostedFile(e.UploadedFile, 3, 320);
        }

        protected void uplImage4_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
        {
            e.CallbackData = SavePostedFile(e.UploadedFile, 4, 320);
        }

        protected void uplImage5_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
        {
            e.CallbackData = SavePostedFile(e.UploadedFile, 5, 320);
        }

        protected void btnOk_Click(object sender, System.EventArgs e)
        {
            if (hdfID.Value.ToString() != "")
                updateProduc();
            else
                createProduct();
        }

        void LoadCBX()
        {
            DataClasses1DataContext dx = new DataClasses1DataContext();
            try
            {
                dx.Connection.Open();
                var list = from k in dx.Categories
                           where k.flag == true
                           select new { k.ID, k.CateName };
                cbloai.DataSource = list;
                cbloai.TextField = "CateName";
                cbloai.ValueField = "ID";
                cbloai.DataBind();
            }
            catch (Exception) { }
            finally { dx.Connection.Close(); }
        }

        protected void uplImage0_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
        {
            e.CallbackData = SavePostedFile(e.UploadedFile, 6, 475);
        }

        void Bindata()
        {
            DataClasses1DataContext dx = new DataClasses1DataContext();

            try
            {
                dx.Connection.Open();
                if (Request.QueryString["k"] != null)
                {
                    hdfID.Value = Request.QueryString["k"];
                    var list = from k in dx.Product_tbs
                               where k.ID == int.Parse(Request.QueryString["k"].ToString())
                               select k;
                    foreach (Product_tb p in list)
                    {
                     
                        txtMetaDescription.Text = p.MetaDescription;
                        txtMetaKeywords.Text = p.MetaKeywords;
                        txtProductname.Text = p.iProName;
                        txtsoluong.Value = p.isoluong;
                        txtNote.Text = p.congty;
                        txtGiamgia.Value = p.giamphantram;
                        txtgia.Value = p.iDongia;
                        cbloai.SelectedItem = cbloai.Items.FindByValue(p.iCateID);
                        cbnhom.SelectedItem = cbloai.Items.FindByValue(p.GroupID);
                        radChitiet.Text = p.iDersc;
                        radHinhanh.Text = p.iPhoto;
                        radTinhnang.Text = p.iTinhnang;
                        radVideo.Text = p.iVideo;
                        //previewImage0.Src = pathUrl+"/"+p.imagLage;
                       // previewImage.Src = pathUrl + "/" + p.image;
                        //previewImage1.Src = pathUrl + "/" + p.hinh1;
                        //previewImage2.Src = pathUrl + "/" + p.hinh2;
                       // previewImage3.Src = pathUrl + "/" + p.hinh3;
                        //previewImage4.Src = pathUrl + "/" + p.hinh4;
                       // previewImage5.Src = pathUrl + "/" + p.hinh5;
                    }
                }
            }
            catch (Exception) { }
            finally { dx.Connection.Close(); }
        }

        void createProduct()
        {
            DataClasses1DataContext dx = new DataClasses1DataContext();
            try
            {
                string chuoi = WebUtils.convertToUnSign3(txtProductname.Text);
                string chuoi1 = chuoi.Replace(" ", "_");
                dx.Connection.Open();
                Product_tb p = new Product_tb();
                p.chuyenhang = cbgiaohang.Text;
                p.iProName = txtProductname.Text;
                p.ipronameSing = chuoi1.Replace(".", "_").Replace("+","").Replace("-","").Replace("*","");
                p.congty = txtNote.Text;
                p.iCateID = int.Parse(cbloai.Value.ToString());
                p.iDersc = radChitiet.Text;
                p.iTinhnang = radTinhnang.Text;
                p.iPhoto = radHinhanh.Text;
                p.iVideo = radVideo.Text;
                p.iVersion = 1;
                p.iview = 0;
                p.isoluong = int.Parse(txtsoluong.Text);
                p.iDongia = float.Parse(txtgia.Value.ToString());
                p.giamphantram = int.Parse(txtGiamgia.Text);
                if (int.Parse(txtGiamgia.Text) > 0)
                    p.iDongiamoi = float.Parse(txtgia.Value.ToString()) - (float.Parse(txtgia.Value.ToString()) * int.Parse(txtGiamgia.Text)) / 100;
                else
                    p.iDongiamoi = float.Parse(txtgia.Value.ToString());
                if (Session["link0"] != null)
                    p.image = Session["link0"].ToString();
                if (Session["link1"] != null)
                    p.hinh1 = Session["link1"].ToString();
                if (Session["link2"] != null)
                    p.hinh2 = Session["link2"].ToString();
                if (Session["link3"] != null)
                    p.hinh3 = Session["link3"].ToString();
                if (Session["link4"] != null)
                    p.hinh4 = Session["link4"].ToString();
                if (Session["link5"] != null)
                    p.hinh5 = Session["link5"].ToString();
                if (Session["link6"] != null)
                    p.imagLage = Session["link6"].ToString();
                p.Chietkhau = int.Parse(txtChietkhau.Text);
                p.iflag = true;
                p.iDatepost = DateTime.Now;
                p.iDateUp = DateTime.Now;
                p.MetaDescription = txtMetaDescription.Text.Trim();
                p.MetaKeywords = txtMetaKeywords.Text.Trim();
                p.GroupID = int.Parse(cbnhom.Value.ToString());
                dx.Product_tbs.InsertOnSubmit(p);
                dx.SubmitChanges();

                lbthongbao.ForeColor = Color.Red;
                lbthongbao.Text = "Sản phẩm đã được cập nhật";
                txtProductname.Text = "";
                txtsoluong.Text = "0";
                txtGiamgia.Text = "0";
                txtNote.Text = "";
                txtChietkhau.Text = "0";
                //  radChitiet.Text = "";
                //  radHinhanh.Text = "";
                // radTinhnang.Text = "";
                //  radVideo.Text = "";

                Session.Remove("link0");
                Session.Remove("link1");
                Session.Remove("link2");
                Session.Remove("link3");
                Session.Remove("link4");
                Session.Remove("link5");
                Session.Remove("link6");
            }
            catch (Exception)
            {
                lbthongbao.ForeColor = Color.Red;
                lbthongbao.Text = "Đã xãy ra lỗi! vui lòng thử lại. Khi thử lại không cần upload lại hình ảnh";
            }
            finally { dx.Connection.Close(); }
        }

        void updateProduc()
        {
            DataClasses1DataContext dx = new DataClasses1DataContext();
            try
            {
                string chuoi = WebUtils.convertToUnSign3(txtProductname.Text);
                string chuoi1 = chuoi.Replace(" ", "_");
                dx.Connection.Open();
                Product_tb p = new Product_tb();
                p = dx.Product_tbs.Single(l => l.ID == int.Parse(hdfID.Value));
                p.iProName = txtProductname.Text;
                p.ipronameSing = chuoi1.Replace(".", "_");
                p.congty = txtNote.Text;
                p.iCateID = int.Parse(cbloai.Value.ToString());
                p.iDersc = radChitiet.Text;
                p.iTinhnang = radTinhnang.Text;
                p.iPhoto = radHinhanh.Text;
                p.iVideo = radVideo.Text;
                p.iVersion = 1;
                p.iview = 0;
                p.isoluong = int.Parse(txtsoluong.Text);
                p.iDongia = float.Parse(txtgia.Value.ToString());
                p.giamphantram = int.Parse(txtGiamgia.Text);
                if (int.Parse(txtGiamgia.Text) > 0)
                    p.iDongiamoi = float.Parse(txtgia.Value.ToString())-(float.Parse(txtgia.Value.ToString()) * int.Parse(txtGiamgia.Text)) / 100;
                else
                    p.iDongiamoi = float.Parse(txtgia.Value.ToString());
                if (Session["link0"] != null)
                    p.image = Session["link0"].ToString();
                if (Session["link1"] != null)
                    p.hinh1 = Session["link1"].ToString();
                if (Session["link2"] != null)
                    p.hinh2 = Session["link2"].ToString();
                if (Session["link3"] != null)
                    p.hinh3 = Session["link3"].ToString();
                if (Session["link4"] != null)
                    p.hinh4 = Session["link4"].ToString();
                if (Session["link5"] != null)
                    p.hinh5 = Session["link5"].ToString();
                if (Session["link6"] != null)
                    p.imagLage = Session["link6"].ToString();
                p.Chietkhau = int.Parse(txtChietkhau.Text);

                p.iDateUp = DateTime.Now;
                p.MetaDescription = txtMetaDescription.Text.Trim();
                p.MetaKeywords = txtMetaKeywords.Text.Trim();
                p.GroupID = int.Parse(cbnhom.Value.ToString());
               
                dx.SubmitChanges();

                lbthongbao.ForeColor = Color.Red;
                lbthongbao.Text = "Sản phẩm đã được cập nhật";
               
                //  radChitiet.Text = "";
                //  radHinhanh.Text = "";
                // radTinhnang.Text = "";
                //  radVideo.Text = "";

                Session.Remove("link0");
                Session.Remove("link1");
                Session.Remove("link2");
                Session.Remove("link3");
                Session.Remove("link4");
                Session.Remove("link5");
                Session.Remove("link6");
            }
            catch (Exception)
            {
                lbthongbao.ForeColor = Color.Red;
                lbthongbao.Text = "Đã xãy ra lỗi! vui lòng thử lại. Khi thử lại không cần upload lại hình ảnh";
            }
            finally { dx.Connection.Close(); }
        }
    }
}